<?php

class ActionSelector {
	

	/**
	 * 
	 * @param TimeMachine $delorean
	 * @throws MissingParamsException
	 * @throws FWerrorException
	 * @return multitype:string string
	 */
	public static function getCtrlAct($delorean) {
		
		$missingParams = array();
		
		if (!isset($_REQUEST['ctrl'])) {
			if (!isset($_REQUEST['act'])) {
				$delorean->clean();
				$_REQUEST['ctrl']	= DEFAULT_CTRL;
				$_REQUEST['act']	= DEFAULT_ACT;
			}
			$missingParams[] = 'ctrl';
		} else {
		
			if (!isset($_REQUEST['act'])) {
				$missingParams[] = 'act';
			}
			
			if (!empty($missingParams)) {
				throw new MissingParamsException($missingParams);
			}
			
			self::findAction($delorean);
			
			if ($_REQUEST['ctrl'] == 'History') {
				
				switch ($_REQUEST['act']) {
	
					case 'back'		: $delorean->back(); break;
					case 'refresh'	: $delorean->refresh(); break;
				
					default		: throw new FWerrorException("method \"TimeMachine::".$_REQUEST['$act']."\" does not exist");
				}
				
				
			}
		}
		
		return array($_REQUEST['ctrl'], $_REQUEST['act']);
		
	}
	/**
	 * 
	 * @param TimeMachine $delorean
	 * @throws FWerrorException
	 */
	public static function findAction($delorean) {
	
		$goback 	= self::backConditions($delorean);
		$gorefresh	= self::refreshConditions($delorean);
	
		if ($goback && $gorefresh) {
			throw new FWerrorException('can not perform both back and refresh -.- check conditions');
		}
	
		if ($goback) {
			$_REQUEST['ctrl']	= 'History';
			$_REQUEST['act']	= 'back';
		}
	
		if ($gorefresh) {
			$_REQUEST['ctrl']	= 'History';
			$_REQUEST['act']	= 'refresh';
		}
	
	}
	
	/**
	 * 
	 * @param TimeMachine $delorean
	 * @return boolean
	 */
	private static function backConditions($delorean) {
		//$c1 = ($_REQUEST['ctrl'] == 'History') && ($_REQUEST['act'] == 'back');
		$prev_req = $delorean->top();
		
		$c1 = isset($_REQUEST['back']) 	&& !(($_REQUEST['ctrl'] == $prev_req['ctrl']) && ($_REQUEST['act'] == $prev_req['act']));
	
	
		return $c1;
	}
	/**
	 * 
	 * @param TimeMachine $delorean
	 * @return boolean
	 */
	private static function refreshConditions($delorean) {
		//$c1 = ($_REQUEST['ctrl'] == 'History') && ($_REQUEST['act'] == 'refresh');
	
		$prev_req = $delorean->top();
		$c2 = ($_REQUEST['ctrl'] == $prev_req['ctrl']) && ($_REQUEST['act'] == $prev_req['act']);
	
		return $c2;
	}	
	
}




?>
